package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"tiktok/model/mysql"
	"tiktok/model/redis"
	"tiktok/tiktokrpc/internal/svc"
	"tiktok/tiktokrpc/tiktokrpc"

	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type TikTokListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewTikTokListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *TikTokListLogic {
	return &TikTokListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *TikTokListLogic) TikTokList(in *tiktokrpc.TikTokListRequest) (*tiktokrpc.TikTokListResponse, error) {
	// todo: add your logic here and delete this line

	var tikTokContents []mysql.TikTokContent

	page := in.Page
	if page <= 0 {
		page = 1
	}

	pageSize := in.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize

	key := fmt.Sprintf("TikTokList%s%d%d", in.Title, in.Page, in.Size)

	get := cache.Redis.Get(l.ctx, key)

	if get.Val() != "" {
		json.Unmarshal([]byte(get.Val()), &tikTokContents)
	} else {
		mysql.DB.Debug().Where("title like ?", "%"+in.Title+"%").Offset(int(offset)).Limit(int(pageSize)).Order("created_at desc").Find(&tikTokContents)

		marshal, _ := json.Marshal(tikTokContents)

		cache.Redis.Set(l.ctx, key, marshal, time.Minute*30)
	}

	var tikTokLists []*tiktokrpc.TikTokList

	for _, content := range tikTokContents {
		list := tiktokrpc.TikTokList{
			Id:    int64(content.ID),
			Title: content.Title,
			Url:   content.Url,
		}

		tikTokLists = append(tikTokLists, &list)
	}

	return &tiktokrpc.TikTokListResponse{List: tikTokLists}, nil
}
